package com.hy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hy.common.Result;
import com.hy.entity.SysUser;
import com.hy.mapper.SysUserMapper;
import com.hy.service.SysLoginService;
import com.hy.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class SysLoginServiceImpl implements SysLoginService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public Result<String> login(String username, String password) {
        //参数校验
        if(StringUtils.isBlank(username) || StringUtils.isBlank(password)){
            return Result.error("账号或密码不能为空");
        }
        //验证用户是否存在
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, username);
        SysUser user = sysUserMapper.selectOne(queryWrapper);
        if(user == null){
            return Result.error("账号不存在");
        }
        //密码校验
        if(!user.getPassword().equals(password)){
            return Result.error("密码错误");
        }
        //生成token
        Map<String, Object> map = new HashMap<>();
        map.put("openid", user.getId());
        map.put("username", user.getUsername());
        return Result.success( "登录成功!",map.toString());
    }
}
